import argparse

from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from client import ChatClient
import uvicorn
import uuid
import asyncio
DEFAULT_SERVERURL="http://localhost:5000"
DEFAULT_NAMESPACE="/socket.io/769ded8b1dc238a56d471b2ea97c57485d72f1089fcde24c6267e4165fec2898"
DEFAULT_ID = uuid.uuid4().hex

'''
python main.py --server http://localhost:5000 --namespace /socket.io/xxx --id 12345
'''
def handle_args():
    parser = argparse.ArgumentParser(description="Run FastAPI with Client")
    parser.add_argument("--server", default=DEFAULT_SERVERURL, help=f"Server URL such as {DEFAULT_SERVERURL}")
    parser.add_argument("--namespace", default=DEFAULT_NAMESPACE,help=f"Socket Namespace such as {DEFAULT_NAMESPACE}")
    parser.add_argument("--id", default=DEFAULT_ID, help=f"Client ID such as {DEFAULT_ID}")
    return parser.parse_args()

args = handle_args()
app = FastAPI()
origins = [
     "*"
]
app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],  # 允许 GET, POST, OPTIONS 等
    allow_headers=["*"],  # 允许所有请求头
)
chat1_client = ChatClient(
    args.server + args.namespace,
    args.namespace,
    id=args.id
)

def init():
    global chat1_client, args

    success = chat1_client.connect()

    if success:
        print("🚀 Successfully connected to server")
        chat1_client.register_route_with_entry(
            "example_route",
            callback=chat1_client.example_route_callback,
            entry={
                "Future": None
            },
            init_data={
                "route": "example_route",
            }
        )
    else:
        print("❌ Failed to connect to server")
#在模块里面调用，确保每次reload都调用
init()

@app.get("/")
def index():
    return {"status": "FastAPI running", "client_id": args.id}

@app.post("/api/chat/send_text")
async def handle_send_text(request: Request):
    body = await request.json()
    question = body.get("question")
    route=body.get("route")
    #print("routes:",chat1_client.routes)
    if not question:
        return {"success": False, "message": "Question is required"}
    if route not in chat1_client.routes:
        return {"success": False, "err_msg": f"Route {route} not registered"}

    future = asyncio.get_event_loop().create_future()
    chat1_client.set_route_future(route, future)
    chat1_client.send_text(route, question)

    try:
        reply = await asyncio.wait_for(future, timeout=120)
        return {"success": True, "reply": reply}
    except asyncio.TimeoutError:
        return {"success": False, "err_msg": "Agent timeout"}
    except Exception as e:
        return {"success": False, "err_msg": f"{e}"}


if __name__ == "__main__":
    #print("route:",chat1_client.routes)
    uvicorn.run(
        "main:app",
        host="127.0.0.1",
        port=5552,
        reload=True
    )